package com.william.xiaobujiantest;

import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.william.xiaobujiantest.Tools.LocationTool.GPSNotInWorkException;
import com.william.xiaobujiantest.Tools.LocationTool.InternetNotInWorkException;
import com.william.xiaobujiantest.Tools.LocationTool.LocationPermissionDeniedException;
import com.william.xiaobujiantest.Tools.LocationTool.LocationTool;
import com.william.xiaobujiantest.Tools.ReceiveResponseThread;
import com.william.xiaobujiantest.Tools.UpdeWidgetTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import static android.content.ContentValues.TAG;

/**
 * 同步天气服务，现获取手机所在经纬度，根据经纬度获取相应位置的天气状况，工作结束后自动关闭
 */
//这里需要改成每小时去同步天气，也必然需要每小时更新一下地理位置
public class WeatherService extends Service {

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HashMap weatherData = parseJSONObjectOrJSONArray((JSONObject)msg.obj);
            RemoteViews rvs = new RemoteViews(getApplicationContext().getPackageName(), R.layout.widget_weather_clock);
            UpdeWidgetTool.updateWeather(getApplicationContext(),rvs,weatherData);
            WeatherService.this.stopSelf();
        }
    };
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind: 服务被绑定！" );
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.e(TAG, "onStartCommand: 服务被启动！" );

        Location location = getLocation();
        if(location!=null) {
            new ReceiveResponseThread(this.handler
                    , location).start();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 获取经纬度
     * @return 数组：0-精度 1-纬度
     */
    private Location getLocation(){
        Location location = null;
        try {

            location = LocationTool.getLocation(this);
        } catch (LocationPermissionDeniedException e) {

            Intent intent = new Intent(this,MainActivity.class);
            intent.putExtra("LocationPermissionDenied",true);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (GPSNotInWorkException e) {

            new  AlertDialog.Builder(this)
                    .setTitle("提示" )
                    .setMessage("本功能需要打开位置服务，用来获取手机位置，并提供相应的天气状况！" )
                    .setPositiveButton("是",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    startActivity(intent);
                                }
                            }
                    ).show();

        } catch (InternetNotInWorkException e) {
            Toast.makeText(this,"没有打开网络",Toast.LENGTH_SHORT).show();

        }
        return location;
    }

    //解析JSON数据
    private HashMap parseJSONObjectOrJSONArray(JSONObject jsonObject) {
        Log.i(TAG, "parseJSONObjectOrJSONArray: "+jsonObject);
        HashMap weatherData = new HashMap();
        String topTemp = "" ;//最高气温
        String cond = "" ;//气象情况
        String lowTemp = "";//最低气温
        String qlty = "";//空气质量

        try {
            JSONObject heWeather = jsonObject.getJSONArray("HeWeather5").getJSONObject(0);
            qlty = heWeather.getJSONObject("aqi").getJSONObject("city").optString("qlty","未知");
            JSONObject weather = (JSONObject) heWeather.getJSONArray("daily_forecast").get(0);
            cond = weather.getJSONObject("cond").optString("txt_d","未知");
            topTemp = weather.getJSONObject("tmp").optString("max","未知");
            lowTemp = weather.getJSONObject("tmp").optString("min","未知");

            weatherData.put("topTemp",topTemp);
            weatherData.put("lowTemp",lowTemp);
            weatherData.put("cond",cond);
            weatherData.put("qlty",qlty);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return weatherData;
    }
}